﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using NetTopologySuite.Mathematics;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml.FormulaParsing.ExpressionGraph.FunctionCompilers;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static org.apache.zookeeper.ZooDefs;

namespace Coldairarrow.Business.Interface
{
    public class DD_DepartmentInterfaceBusiness : DDInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption DD_Query { get; set; }
        //部门请求数据
        public DD_ReqDTO_Dep DD_ReqDTO_Dep { get; set; }
        public DD_DepartmentInterfaceBusiness()
        {
            this.InterfaceName = "钉钉获取部门";
            //索引字段
            this.MapFields = GetMapField("DD_Get");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            DD_Query = this.interfaceOption.Where(x => x.OperateType == "DD_Get").First();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            //this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

            DD_ReqDTO_Dep = new DD_ReqDTO_Dep();
        }



        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, DD_QueryEventArgs queryEventArgs)
        {
            try
            {
                //获取appId
                var key = JObject.Parse(DD_Query.TargetLoginData);
                queryEventArgs.UrlQuery.AppKey = key["appkey"].Value<string>();
                queryEventArgs.UrlQuery.AppSecret = key["appsecret"].Value<string>();
                queryEventArgs.UrlQuery.Corpid = key["corpid"].Value<string>();
                queryEventArgs.UrlQuery.Corpsecret = key["corpsecret"].Value<string>();
                //获取token
                JObject token = JObject.Parse(GetToken(queryEventArgs.UrlQuery));
                queryEventArgs.UrlQuery.Token = token["access_token"].ToString();
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, DD_QueryEventArgs queryEventArgs)
        {
            if (!string.IsNullOrEmpty(queryEventArgs.UrlQuery.Token))
            {
                //获取拼接token的URL
                queryEventArgs.HttpClient.Url = $"{DD_Query.TargetUrl}?access_token={queryEventArgs.UrlQuery.Token}";
                queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, DD_ReqDTO_Dep);
            }
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, DD_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                DD_DepartmentDTO result = (DD_DepartmentDTO)JsonConvert.DeserializeObject<DD_DepartmentDTO>(queryEventArgs.ResultStr);
                if (result.errmsg == "ok")
                {
                    queryEventArgs.Success = true;
                    queryEventArgs.Rows = result.result;
                    queryEventArgs.Page.Complete = true;
                }
                else
                {
                    queryEventArgs.Success = false;
                }
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async Task<List<DD_DepartmentDTO.Department>> ExecuteInterface()
        {


            List<DD_DepartmentDTO.Department> depList = new List<DD_DepartmentDTO.Department>();
            try
            {
                //获取部门列表
                List<DD_DepartmentDTO.Department> processDTO = await this.QueryAsync<DD_DepartmentDTO.Department>(this.DD_Query, SqlDb);
                if (processDTO.Count > 0)
                {
                    depList.AddRange(processDTO);
                    foreach (DD_DepartmentDTO.Department department in processDTO)
                    {
                        var chiles = await GetDepList(department);
                        depList.AddRange(chiles);

                    }

                }
            }
            catch (Exception ex)
            {

                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");

            }

            return depList;
        }

        public async Task<List<DD_DepartmentDTO.Department>> GetDepList(DD_DepartmentDTO.Department dep)
        {
            try
            {
                //钉钉请求的参数
                this.DD_ReqDTO_Dep.dept_id = dep.dept_id.ToString();
                List<DD_DepartmentDTO.Department> processDTO = await this.QueryAsync<DD_DepartmentDTO.Department>(this.DD_Query, SqlDb);
                List<DD_DepartmentDTO.Department> chiles = new List<DD_DepartmentDTO.Department>();
                if (processDTO.Count > 0)
                {
                    foreach (DD_DepartmentDTO.Department department in processDTO)
                    {
                        var temp = await GetDepList(department);
                        chiles.AddRange(temp);
                    }
                    processDTO.AddRange(chiles);
                }

                return processDTO;
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
                return null;
            }
        }

        /// <summary>
        /// 接口发送请求获取TOKEN
        /// </summary>
        /// <param name="ol_key"></param>
        /// <returns></returns>
        public string GetToken(DD_UrlQuery query)
        {
            //1.获取Token
            HttpClient httpClient = new HttpClient();
            httpClient.Method = "GET";
            // 设置请求参数
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat($"https://oapi.dingtalk.com/gettoken?");
            sb.AppendFormat($"appkey={query.AppKey}&");
            sb.AppendFormat($"appsecret={query.AppSecret}&");
            sb.AppendFormat($"corpid={query.Corpid}&");
            sb.AppendFormat($"corpsecret={query.Corpsecret}");
            httpClient.Url = sb.ToString();
            string sysReportResul1t = httpClient.Request();
            if (!sysReportResul1t.IsNullOrEmpty())
            {
                return sysReportResul1t;

            }
            else
            {
                return "";

            }
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
